package com.example.feature.demo.config;

import org.hibernate.validator.HibernateValidatorConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.support.ResourceBundleMessageSource;
import org.springframework.validation.beanvalidation.LocalValidatorFactoryBean;

import javax.validation.Validator;

/**
 * ValidationConfiguration
 *
 * @author zhouxianfeng
 * @date 2021-4-14
 */
@Configuration
public class ValidationConfiguration {

    @Bean
    public Validator defaultValidator() {
        MyLocalValidatorFactoryBean factoryBean = new MyLocalValidatorFactoryBean();
        ResourceBundleMessageSource resourceBundleMessageSource = new ResourceBundleMessageSource();
        resourceBundleMessageSource.setBasename("messages.paramException");
        factoryBean.setValidationMessageSource(resourceBundleMessageSource);
        return factoryBean;
    }

    public class MyLocalValidatorFactoryBean extends LocalValidatorFactoryBean {
        @Override
        protected void postProcessConfiguration(javax.validation.Configuration<?> configuration) {
            if (configuration instanceof HibernateValidatorConfiguration) {
                HibernateValidatorConfiguration hibernateValidatorConfiguration = (HibernateValidatorConfiguration) configuration;
                hibernateValidatorConfiguration.allowMultipleCascadedValidationOnReturnValues(true)
                        .allowOverridingMethodAlterParameterConstraint(true)
                        .allowParallelMethodsDefineParameterConstraints(true);
            }
        }
    }

}
